const express = require("express");
const router = express.Router();
const jwt = require("jsonwebtoken");
const appConfig = require("../../config/config");

const AdminInfoModel = require("../../model/AdminInfoModle");

router.get("/", (req, res) => {
    res.send("v1 api");
});

router.post("/login", async(req, res) => {
    const param = req.body;
    let info = await AdminInfoModel.findOne({
        username: param.username,
        password: param.password,
    });
    if (info) {
        let userId = {
            _id: info._id.toString(),
        };
        res.jsonp({
            status: 200,
            message: "登录成功",
            username: info.username,
            token: "Bearer " +
                jwt.sign(userId, appConfig.secret, {
                    expiresIn: "2h", // "1day" 以秒表示或描述时间跨度zeit / ms的字符串。如60，“2 days”，“10h”，“7d”
                }),
            /**
             * jwt解密, 注意 加密和解密时 secret 需要一致
             */
            // jwt.verify(userToken, secret, (err, result) => {
            //     if (err) {
            //         // throw err 说明用户的 session_key 过期，需要重新登录
            //         res.json({ msg: "无效的token或token已过期" });
            //     } else {
            //         res.json(result);
            //     }
            // });
        });
    } else {
        res.jsonp({
            status: 400,
            message: "用户名或密码错误",
        });
    }
});
router.post("/authentication", (req, res) => {
    // console.log();
    // console.log(req.headers);
    let token = req.headers["authorization"].split(" ")[1];
    let resObj = {
        status: 200,
        message: "ok",
    };
    // console.log(token);
    if (token) {
        // 解密
        jwt.verify(token, appConfig.secret, (err, result) => {
            if (err) {
                if (err.name == "TokenExpiredError") {
                    resObj = {
                        status: 300,
                        message: "token过期",
                    };
                } else {
                    resObj = {
                        status: 400,
                        message: "无效的token",
                    };
                }
            } else {
                // console.log(result); // { _id: '62add353a38f4eabd6de8a9f', iat: 1655973472, exp: 1655974072 }
            }
        });
    }
    res.jsonp(resObj);
});

router.get("/students", (req, res) => {
    res.jsonp({
        status: 200,
        message: "服务器数据",
    });
});

router.get("/test", (req, res) => {
    res.jsonp({
        status: 200,
        message: "服务器数据",
    });
});

module.exports = router;